package uk.co.richardwkirk.parkrun.android.news;

import uk.co.richardwkirk.parkrun.android.AppSettings;
import uk.co.richardwkirk.parkrun.android.IntentExtras;
import uk.co.richardwkirk.parkrun.android.ParkrunEventData;
import uk.co.richardwkirk.parkrun.android.dataload.LoadDataDisplay;
import uk.co.richardwkirk.parkrun.android.dataload.cache.NewsCache;
import uk.co.richardwkirk.parkrun.news.NewsFeed;
import uk.co.richardwkirk.parkrun.news.NewsItem;
import uk.co.richardwkirk.parkrun.news.NewsSubject;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class NewsDisplay extends ListActivity {

	
	private static final int REQUEST_NEWS_LOAD_FEED = 20;

	ArrayAdapter<String> adapter = null;
	
	// Hold a pointer to the news so it won't be garbage collected
	// from the NewsCache
	NewsFeed currentNews = null;
	String newsFeedUrl = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Get a list adapter to add the array values into the list
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
		setListAdapter(adapter);
		
		// Have we already loaded the news feed?
		doNewsLoad();
	}
	
	private void doNewsLoad() {
		// Get the news subject
		NewsSubject newsSubject = getNewsSubject();
		
		// Set the title while we load the news
		if (newsSubject == null) {
			failedNewsLoad("News subject not found.");
		}
		else {
			// Check to see if we have already loaded the news feed
			newsFeedUrl = newsSubject.getNewsFeedUrl();
			Log.d("PARKRUN", "Getting news from [" + newsFeedUrl + "]");
			NewsFeed newsFeed = NewsCache.getSingleton().getItem(newsFeedUrl);
			if (newsFeed != null) {
				// If we have we just display it
				updateNews(newsFeed);
			}
			else {
				// Otherwise we start the load data activity to get it
				Intent loadDataIntent = new Intent(this, LoadDataDisplay.class);
				loadDataIntent.putExtra(IntentExtras.EXTRA_DATA_LOAD_TYPE, IntentExtras.DATA_LOAD_TYPE_NEWS_FEED);
				loadDataIntent.putExtra(IntentExtras.EXTRA_DATA_LOAD_ID, newsFeedUrl);
				startActivityForResult(loadDataIntent, REQUEST_NEWS_LOAD_FEED);
			}
		}
	}
	

	public NewsSubject getNewsSubject() {
		Intent intent = getIntent();
		NewsSubject newsSubject = null;
		String eventType = intent.getStringExtra(IntentExtras.EXTRA_NEWS_TYPE);
		if (IntentExtras.EXTRA_NEWS_TYPE_EVENT.equals(eventType)) {
			String eventShortName = intent.getStringExtra(IntentExtras.EXTRA_SELECTED_EVENT);
			Log.d("PARKRUN", "Getting news for event: " + eventShortName);
			newsSubject = ParkrunEventData.getSingleton().getWorld().getEvent(eventShortName);
		}
		else if (IntentExtras.EXTRA_NEWS_TYPE_COUNTRY.equals(eventType)) {
			String countryName = intent.getStringExtra(IntentExtras.EXTRA_SELECTED_COUNTRY);
			Log.d("PARKRUN", "Getting news for country: " + countryName);
			newsSubject = ParkrunEventData.getSingleton().getWorld().getRegion(countryName);
		}
		return newsSubject;
	}	
	

	/**
	 * Update the news in the WebView
	 */
	public void updateNews(NewsFeed news) {
		Log.d("PARKRUN", "News feed has loaded.");
		currentNews = news;
		if (currentNews != null) {
			for (NewsItem item : currentNews) {
				adapter.add(item.getTitle());
			}
		}
	}


	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// View the selected news item
		Log.d("PARKRUN", "Opening news content display for article: " + position);
		Intent intent = new Intent(this, NewsContentDisplay.class);
		intent.putExtra(IntentExtras.EXTRA_NEWS_FEED_URL, newsFeedUrl);
		intent.putExtra(IntentExtras.EXTRA_NEWS_ITEM_NUMBER, position);
		startActivityForResult(intent, 0);
	}
	
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if (requestCode == REQUEST_NEWS_LOAD_FEED)
		{
			handleNewsFeedLoad(resultCode);
		}
	}

	private void handleNewsFeedLoad(int resultCode) {
		// We have received the news feed data load response.
		NewsFeed newsFeed = null;
		if (resultCode == Activity.RESULT_OK) {
			newsFeed = NewsCache.getSingleton().getItem(newsFeedUrl);
		}
		
		// Update the news on the display
		if (newsFeed != null) {
			updateNews(newsFeed);
		}
		else {
			failedNewsLoad("Failed to load news feed.");
		}
	}
	
	
	private void failedNewsLoad(String reason) {
		Toast toast = Toast.makeText(getApplicationContext(), reason, AppSettings.WARNING_DISPLAY_TIME);
		toast.show();
		finish();
	}
	
}
